package cool.webstudy.admin.configuration.security;

import cool.webstudy.admin.filter.security.JWTAuthenticationFilter;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Collections;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Resource
    private JWTAuthenticationFilter jwtAuthenticationFilter;

    /**
     * 配置HTTP请求的安全性规则，禁用CSRF保护，设置会话管理策略为无状态，并指定某些路径可以匿名访问，其他路径需要进行身份验证
     *
     * @param http
     * @throws Exception
     */
    @Bean
    protected SecurityFilterChain configure(HttpSecurity http) throws Exception {
        //禁用CSRF（跨站请求伪造）保护，因为在无状态的JWT认证中，不需要使用CSRF保护。
        http.csrf(AbstractHttpConfigurer::disable);
        //跨域访问配置
        http.cors().configurationSource(corsConfigSource());
        http.authorizeHttpRequests((requestAuth) -> {
                    requestAuth
                            .anyRequest().permitAll(); // 其他请求必须经过身份验证
                })
                //设置会话管理策略为无状态，即不创建和使用会话。
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)  // 设置为无状态会话
                )
                .httpBasic(b -> {
                    b.disable();
                })
                .formLogin(form -> {
                    form.disable();
                })
                //将自定义的过滤器添加到链中
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }
    //跨域配置
    private CorsConfigurationSource corsConfigSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        configuration.setAllowedOrigins(Collections.singletonList("*"));
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
